<template>
  <div class="">
    <h1>监听属性</h1>
    <button @click="num++">num++</button>
    <button @click="change">改变名字</button>
    <hr />

    <input type="text" v-model="name" />
    <input type="text" v-model="age" />
    <button @click="add">add</button>
    <ul>
      <li v-for="(item, index) in list" :key="index">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 0,
      obj: {
        name: "小明",
      },
      list: [
        { name: "小明", age: 18 },
        { name: "小宏", age: 20 },
      ],
      name: "",
      age: "",
    };
  },
  mounted() {
    if (localStorage.getItem("list")) {
      this.list = JSON.parse(localStorage.getItem("list"));
    }
    //如果本地存储中有就把本地存储中的数据拿过来用
  },
  methods: {
    change() {
      this.obj.name = "小红";
    },
    add() {
      this.list.push({ name: this.name, age: this.age });
    },
  },
  components: {},
  watch: {
    // num: {
    //   handler(newval, oldval) {
    //     console.log(newval, oldval);
    //   }, //执行函数，当num发生改变就会执行
    //   immediate: true, //是否一进入页面就执行监听函数，默认的是false
    //   deep: true, //深度监听
    // },
    obj: {
      handler(newval, oldval) {
        console.log(newval, oldval);
      }, //执行函数，当num发生改变就会执行
      immediate: true, //是否一进入页面就执行监听函数，默认的是false
      deep: true, //深度监听
    },

    // 监听属性可以简写,只有一个执行函数handler
    num(newval, oldval) {
      console.log(newval);
    },
    list(newval) {
      localStorage.setItem("list", JSON.stringify(newval));
    },
    //只要list一发生变化就会把新值存在本地存储中
  },
};
</script>

<style lang="scss"></style>
